<template>
  <van-notice-bar
      left-icon="volume-o"
      color="#1989fa" background="#ecf9ff"
      text="欢迎使用爱联学习交友平台，在这里你可以寻找你的学习搭子，本平台支持匹配相同爱好的程序员朋友和聊天功能，请大家遵守网络安全法，做一个遵纪守法的好程序员！"
  />
  <van-search v-model="searchText" placeholder="搜索附近用户" @search="onSearch(searchText)"/>
  <van-cell center title="心动模式">
    <template #right-icon>
      <van-switch v-model="isMatchMode" size="24" @change="onMatchModeChange"/>
    </template>
  </van-cell>

  <user-card-list :user-list="userList" :loading="loading"/>
  <van-back-top right="15vw" bottom="10vh" />
  <div style="display: flex; justify-content: center;">
    <infinite-loading :identifier="infiniteId" @infinite="loadMore" v-if="!isMatchMode"/>
  </div>
  <van-empty v-if="!userList || userList.length < 1" description="数据为空"/>
</template>

<script setup lang="ts">
import {ref, onMounted} from "vue";

import myAxios from "../plugins/myAxios.ts";
import UserCardList from "../components/UserCardList.vue";
import {UserType} from "../models/user"
import {showToast} from "vant";
import InfiniteLoading from "v3-infinite-loading";

const searchText = ref('');
const userList = ref<UserType[]>([]);
const isMatchMode = ref<boolean>(false);
const loading = ref(true);
const infiniteId = ref(+new Date()); // 使用时间戳作为唯一标识

let pageNum = 1;
let hasMoreData = ref(true);
let lastLoadTime = 0;
let isLoading = false; // 请求锁

/**
 * 加载数据
 */
const loadData = async () => {
  if (isLoading) return;
  isLoading = true;
  let userListData: any;

  try {
    loading.value = true;

    if (isMatchMode.value) {
      const num = 10;
      const response = await myAxios.get('/user/match', { params: { num } });
      userListData = response?.data;
    } else {
      const response = await myAxios.get('/user/recommend', {
        params: { pageSize: 4, pageNum }
      });
      userListData = response?.data;
    }

    if (userListData) {
      userListData.forEach((user: UserType) => {
        if (user.tags) user.tags = JSON.parse(user.tags);
      });

      if (isMatchMode.value) {
        userList.value = userListData;
        hasMoreData.value = false;
      } else {
        userList.value = pageNum === 1
            ? userListData
            : [...userList.value, ...userListData];
        hasMoreData.value = userListData.length >= 4;
      }
    }
  } catch (error) {
    console.error('请求失败:', error);
    showToast('数据加载失败');
    hasMoreData.value = false;
  } finally {
    loading.value = false;
    isLoading = false;
  }
};

// 模式切换处理
const onMatchModeChange = async () => {
  // 重置所有分页状态
  pageNum = 1;
  hasMoreData.value = true;
  userList.value = [];
  lastLoadTime = 0;
  infiniteId.value = +new Date(); // 刷新无限滚动组件

  const toast = showToast({
    type: 'loading',
    message: `${isMatchMode.value ? '开启' : '关闭'}心动模式中...`,
    forbidClick: true,
    duration: 1000
  });

  try {
    await loadData();
    showToast({
      message: `${isMatchMode.value ? '已开启' : '已关闭'}心动模式`,
      type: 'success',
      duration: 1000
    });
  } catch (error) {
    showToast('模式切换失败');
    isMatchMode.value = !isMatchMode.value; // 回滚开关状态
  } finally {
    toast.close();
  }
};

// 滚动加载更多
const loadMore = () => {
  if (!hasMoreData.value || isLoading) return;

  const now = Date.now();
  if (now - lastLoadTime < 500) return;

  lastLoadTime = now;
  pageNum++;
  loadData();
};

// 搜索处理
const onSearch = async (searchText: string) => {
  if (isLoading) return;
  isLoading = true;

  try {
    loading.value = true;
    const res = await myAxios.get('/user/searchNearby', {
      params: { radius: searchText }
    });

    if (res?.code === 0) {
      const userListData = res.data || [];
      userListData.forEach((user: UserType) => {
        if (user.tags) user.tags = JSON.parse(user.tags);
      });
      userList.value = userListData;
    }
  } catch (error) {
    console.error('搜索失败:', error);
    showToast('搜索失败');
  } finally {
    loading.value = false;
    isLoading = false;
  }
};

// 初始加载
onMounted(() => {
  loadData();
});
</script>
